#include "OpenGLShader.h"

#include <glad/glad.h>

namespace Fysics
{
	OpenGLShader::OpenGLShader(const std::string& srcCode, ShaderType type)
		: Shader(type)
	{
		CompileShader(srcCode);
	}

	OpenGLShader::~OpenGLShader()
	{
		glDeleteShader(m_RendererID);
	}

	void OpenGLShader::Delete()
	{
		glDeleteShader(m_RendererID);
	}

	void OpenGLShader::CompileShader(const std::string& sourceCode)
	{		
		// Create an empty shader handle
		if (m_Type == ShaderType::VERTEX)
		{
			m_RendererID = glCreateShader(GL_VERTEX_SHADER);
		}
		else if (m_Type == ShaderType::FRAGMENT)
		{
			m_RendererID = glCreateShader(GL_FRAGMENT_SHADER);
		}
		else
		{
			m_RendererID = 0;
			return;
		}

		// Send the shader source code to GL
		const GLchar* source = sourceCode.c_str();
		glShaderSource(m_RendererID, 1, &source, 0);
		// Compile the vertex shader
		glCompileShader(m_RendererID);

		GLint isCompiled = 0;
		glGetShaderiv(m_RendererID, GL_COMPILE_STATUS, &isCompiled);
		if (isCompiled == GL_FALSE)
		{
			GLint maxLength = 0;
			glGetShaderiv(m_RendererID, GL_INFO_LOG_LENGTH, &maxLength);
			char* infoLog = new char[maxLength];
			glGetShaderInfoLog(m_RendererID, maxLength, &maxLength, infoLog);
			std::string type;
			if (m_Type == ShaderType::VERTEX)
				type = "VertexShader:\n";
			else if (m_Type == ShaderType::FRAGMENT)
				type = "FragmentShader:\n";
			std::cout << type << infoLog << std::endl;
			delete[] infoLog;

			glDeleteShader(m_RendererID);
			return;
		}
	}
}